<template>
  <el-dialog title="入住登记" :close-on-click-modal="false" :visible.sync="flag" @open="handlerDialogOpen" @close="handlerDialogClose">

    <el-steps :active="activeStep" :process-status="activeStatus" finish-status="success">
      <el-step title="填写客户信息"></el-step>
      <el-step title="办理入住"></el-step>
    </el-steps>


    <el-form v-show="activeStep===0" :model="customerForm" :rules="customerDataRule" ref="customerForm"
      @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="身份证号" prop="identityNumber">
        <el-autocomplete v-model="customerForm.identityNumber" :fetch-suggestions="querySearchAsync"
          placeholder="请输入身份证号" @select="handleSelect"  :clearable="true"
          @blur="checkIdentityNumber(customerForm.identityNumber,false)" @clear="clearAll" >
          <template slot-scope="{ item }">
            <span style="color: #11c2a8;">{{ item.value }}</span><br>
            <span style="color: silver;font-style: italic;">{{ item.name }}-{{ item.address }}</span>
          </template>
          </el-autocomplete>
          <i class="el-icon-info" style="color:silver">系统如果检索到存在为该身份证号码的顾客会自动填写</i>
      </el-form-item>
      <el-form-item label="客户姓名" prop="name">
        <el-input v-model="customerForm.name" placeholder="客户姓名" :disabled="!canModify" @focus="checkIdentityNumber(customerForm.identityNumber,true)"></el-input>
      </el-form-item>
      <el-form-item label="客户头像" prop="headImgUrl">
        <single-upload v-model="customerForm.headImgUrl" ref="singleUpload" :disabled="!canModify"></single-upload>
      </el-form-item>
      <el-form-item label="客户性别" prop="gender">
        <el-radio-group v-model="customerForm.gender" size="small" :disabled="!canModify">
          <el-radio-button label="1">男</el-radio-button>
          <el-radio-button label="0">女</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker v-model="customerForm.birthday" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd HH:mm:ss"
          align="right" type="date" placeholder="选择日期" :picker-options="pickerOptions" :disabled="!canModify">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="customerForm.phone" placeholder="手机号码" :disabled="!canModify"></el-input>
      </el-form-item>
      <el-form-item label="血型" prop="bloodType">
        <el-select placeholder="请选择供应血型" v-model="customerForm.bloodType" :disabled="!canModify">
          <el-option v-for="item in bloodType" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="家庭地址" prop="address">
        <el-row>
          <el-col :span="12">
            <select-address @fromComponentAddress="fromComponentAddress" ref="selectAddress" :Address="address" :disabled="!canModify"></select-address>
          </el-col>
          <el-col :span="12">
            <el-input v-model="addressFloor" placeholder="请输入详细楼牌(此处选填)" :disabled="address.length===0 * !canModify || isFoundID"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>


   <el-form v-show="activeStep===1" :model="checkInForm" :rules="checkInDataRule" ref="checkInForm"
      @keyup.enter.native="dataFormSubmit()" label-width="80px" :disabled="checkInDisable">
      <el-form-item label="床位编号" prop="bedId">
        <el-select v-model="checkInForm.bedId" placeholder="请选择床位">
          <el-option
            v-for="item in bedList"
            :key="item.bedId"
            :label="'编号: '+item.bedId"
            :value="item.bedId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="checkInForm.startTime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
          align="right" type="datetime" placeholder="选择服务开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="checkInForm.endTime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
          align="right" type="datetime" placeholder="选择服务结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户状态" prop="validState">
        <el-radio-group v-model="checkInForm.validState=1" size="small">
          <el-radio-button label="1">在住</el-radio-button>
          <el-radio-button label="0" :disabled="true">退住</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>





    <span slot="footer" class="dialog-footer">
      <el-button @click="flag = false">取消</el-button>
      <el-button v-if="activeStep>0" @click="back">上一步</el-button>
      <el-button type="primary" @click="next(activeStep)" v-if="activeStatus!=='error'">{{activeStep===0?"下一步":"提交"}}</el-button>
    </span>
  </el-dialog>

</template>

<script>
  import selectAddress from "../select-address/SelectAddress.vue"
  import singleUpload from "../upload/singleUpload.vue"
  export default {
    watch: {
      address: {
        handler(newName, oldName) {
          if(newName.length>0){
            this.customerForm.address=newName.join("/")
          }else{
            this.customerForm.address="";
          }
        },
        deep: true,
        immediate: true
      }
    },
    components: {
      selectAddress,
      singleUpload
    },
    data() {
      return {
        previewCustomerList:[],
        bedList : [],
        state: '',
        timeout:  null,
        activeStep: 0,
        activeStatus:"process",
        flag: false,
        isFoundID:false,
        canModify:true,
        checkInDisable:false,
        bloodType:[
          {value:"A",label:"A型"},
          {value:"B",label:"B型"},
          {value:"AB",label:"AB型"},
          {value:"O",label:"O型"}
        ],
        address: [],
        addressFloor: "",
        customerForm: {
          id: 0,
          name: '',
          headImgUrl: '',
          gender: '',
          identityNumber: '',
          birthday: '',
          phone: '',
          bloodType: '',
          address: '',
          createTime: '',
          updateTime: '',
          isDelete: ''
        },
        customerDataRule: {
          name: [{
            required: true,
            message: '客户姓名不能为空',
            trigger: 'change'
          }],
          headImgUrl: [{
            required: true,
            message: '客户头像不能为空',
            trigger: 'change'
          }],
          gender: [{
            required: true,
            message: '客户性别不能为空',
            trigger: 'change'
          }],
          identityNumber: [{
            required: true,
            message: '身份证号码不能为空',
            trigger: 'blur'
          },{ pattern: /^(\d{6})(19|20|21)(\d{2})(1[0-2]|0[1-9])(0[1-9]|[1-2][0-9]|3[0-1])(\d{3})(\d|X|x)?$/, message: '身份证格式有误', trigger: 'change' }],
          birthday: [{
            required: true,
            message: '出生日期不能为空',
            trigger: 'change'
          }],
          phone: [{
            required: true,
            message: '手机号码不能为空',
            trigger: 'change'
          },{ pattern: /^((13[0-9])|(14[5-8])|(15([0-3]|[5-9]))|(16[6])|(17[0|4|6|7|8])|(18[0-9])|(19[8-9]))\d{8}$/, message: '手机号格式有误', trigger: 'change' }],
          bloodType: [{
            required: true,
            message: '血型不能为空',
            trigger: 'change'
          }],
          address: [{
            required: true,
            message: '家庭地址不能为空',
            trigger: 'change'
          }]
        },
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前的今天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        checkInForm: {
          customerId: '',
          bedId: '',
          startTime: '',
          endTime: '',
          validState: ''
        },
        checkInDataRule: {
          bedId: [{
            required: true,
            message: '床位id:参照床位表中的主键id不能为空',
            trigger: 'blur'
          }],
          startTime: [{
            required: true,
            message: '服务开始时间不能为空',
            trigger: 'blur'
          }],
          endTime: [{
            required: true,
            message: '服务结束时间不能为空',
            trigger: 'blur'
          }],
          validState: [{
            required: true,
            message: '客户状态:',
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      clearAll(){
        if(this.isFoundID){
          // 在选择已有客户档案的情况下，全部清空
          this.handlerDialogOpen();
        }
      },
      querySearchAsync(queryString, cb) {
        var previewCustomerList = this.previewCustomerList;
        var results = queryString ? previewCustomerList.filter(this.createStateFilter(queryString)) : previewCustomerList;
        console.log(results.length,results,this.isFoundID,this.customerForm);
        if(this.isFoundID){
          if(results.length<=0){
            // 关闭禁用
            this.shouldDisabled(false);
          }else{
            results.forEach((v,i)=>{
              if(v.id===this.customerForm.id&&v.identityNumber!==this.customerForm.identityNumber){
                // 关闭禁用
                this.shouldDisabled(false);
              }
            })
          }

        }
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 100);
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      checkIdentityNumber(idcard,isFocus){
        let x = idcard.trim()||null;
        console.log("x",x);
        if(x){
          // 校验填写的身份证号是否存在预选列表中
          let arr= [...this.previewCustomerList];
          arr=arr.filter((v,i)=>x===v.identityNumber&&v.identityNumber.length>0);
          console.log("arr",arr);
          if(arr.length>0){
            this.$message.success("检测到客户档案库中含有此客户");
            this.handleSelect({...arr[0]});
          }else{
            if(isFocus){
              this.$message.info("检测到客户档案库中没有此客户,提交成功后会保存改客户档案");
            }
          }
        }
      },
      shouldDisabled(e){
        let flag= e||false;
        // 禁用所有输入框
        this.canModify=!flag;
        this.isFoundID=flag;
        // 禁用上传组件
        this.$refs.singleUpload.setDisabled(flag);
        this.$refs.selectAddress.setDisabled(flag);
      },
      handleSelect(item) {
        console.log({...item});
        // 对表单数据进行赋值
        this.customerForm={...item};
        // 地址分组回显
        let arr=item.address.split("/");
        this.addressFloor=arr.pop();
        this.address=arr;
        // 开启禁用
        this.shouldDisabled(true);
      },
      fromComponentAddress(childValue){
        this.address=childValue;
        console.log("d",this.address);
      },
      openInit() {
        this.flag = true
        // 重置表单
      },
      next(mode) {
        if(mode===0){
          // 需要校验表单-校验通过再放行到下一步
          this.address.push(this.addressFloor)
          this.customerForm.address=this.address.join("/");
          this.customerForm={...this.customerForm,isFound:this.isFoundID};
          this.$refs['customerForm'].validate((valid) => {
            if(valid){
              // 校验通过还需验证此用户是否存在在住的住房信息
              if(this.isFoundID){
                this.$http({
                  url: this.$http.adornUrl('/customer/infocheckin/isCheckIn?customerId='+this.customerForm.id),
                  method: 'get',
                }).then(({data})=>{
                  if(data && data.code === 0){
                    if(data.isCheckIn===false){
                      this.$message.success("可以为此客户办理入住");
                      // 设置步骤条当前状态
                      this.activeStatus="process";
                      this.checkInDisable=false;
                    }else{
                      this.$message.warning("此客户已经入住了，无需再次办理入住");
                      // 设置步骤条当前状态
                      this.activeStatus="error";
                      this.checkInForm=data.bean;
                      this.checkInDisable=true;
                    }
                  }else{
                    this.$message.error(data.msg);
                  }
                })
              }
              this.activeStep++;
              console.log(this.customerForm);
            }else{
              this.$message.error("请先完善客户信息再进行下一步操作")
            }
          })

        }
        if(mode===1){
          // 提交之前，验证入住登记表单
          this.$refs['checkInForm'].validate((valid) => {
            if (valid) {
              // 校验成功
              // 由于mode===0的时候已经设置了提交按钮的显示状态，说明此时就是为未入住的客户进行办理入住
              // 未入住的客户有两种：
              if(!this.customerForm.isFound){
                // ② 未在籍的客户：需要再次保存客户信息到档案表
                console.log('未在籍的客户：需要再次保存客户信息到档案表');
                // 保存客户信息到档案表并获取到id
                this.$http({
                  url: this.$http.adornUrl(`/customer/infocusomerrecords/addCustomer`),
                  method: 'post',
                  data: this.$http.adornData({
                    'name': this.customerForm.name,
                    'headImgUrl': this.customerForm.headImgUrl,
                    'gender': this.customerForm.gender,
                    'identityNumber': this.customerForm.identityNumber,
                    'birthday': this.customerForm.birthday,
                    'phone': this.customerForm.phone,
                    'bloodType': this.customerForm.bloodType,
                    'address': this.customerForm.address
                  })
                }).then(({data}) => {
                  if (data && data.code === 0&&data.customerId) {
                    // 接收到customerId了, 插入入住信息
                    this.checkInFormSubmit(data.customerId)
                  }
                })
              }else{
                // ① 已在籍的客户：无需再次保存客户信息到档案表
                console.log('已在籍的客户：无需再次保存客户信息到档案表');
                this.checkInFormSubmit(this.customerForm.id)
              }
            }
          })

        }
      },
      back(){
        this.activeStep--;
        this.activeStatus="process";
      },
      checkInFormSubmit(customerId){
        console.log(customerId);
        if(!customerId){
          return;
        }
        this.$http({
          url: this.$http.adornUrl(`/customer/infocheckin/save`),
          method: 'post',
          data: this.$http.adornData({
            'customerId': customerId,
            'bedId': this.checkInForm.bedId,
            'startTime': this.checkInForm.startTime,
            'endTime': this.checkInForm.endTime,
            'validState': this.checkInForm.validState,
          })
        }).then(({data})=>{
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.flag = false
                this.$emit('refreshDataList')
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      dataFormSubmit() {
        this.flag = false
      },
      handlerDialogClose(){
        this.activeStep=0;
        this.activeStatus='process';
        this.checkInDisable=false;
      },
      handlerDialogOpen() {
        // 首先应清空表单
        this.$nextTick(() => {
          this.$refs['customerForm'].resetFields();
          this.address=[];
          this.addressFloor="";
          this.$refs['checkInForm'].resetFields();
          // 关闭禁用
          this.shouldDisabled(false);
        });
        // 获取客户列表
        this.getCustomerList();
        this.getBedList();
      },
      getCustomerList() {
        // 获取已在籍的顾客档案信息
        this.$http({
          url: this.$http.adornUrl('/customer/infocusomerrecords/customerlist'),
          method: 'get',
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.previewCustomerList = data.data
            this.previewCustomerList = this.previewCustomerList.map((v) => v = { ...v, value: v.identityNumber})
          } else {
            this.dataList = []
          }
        })
      },
      getBedList() {
        // 获取已在籍的顾客档案信息
        this.$http({
          url: this.$http.adornUrl('/cw/cwbed/getBedList'),
          method: 'get',
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.bedList = data.data
          } else {
            this.bedList = []
          }
        })
      },
    }
  }
</script>

<style>
</style>
